package top.superflow.version.structure

import org.apache.commons.lang3.StringUtils
import org.reflections.Reflections
import shapeless.TypeCase
import top.superflow.exception.RequestUnsupportedException
import top.superflow.verify.Ensure
import top.superflow.version.db.jpa.JpaEntityVersion

import scala.collection.JavaConverters._
import scala.collection.{Set, mutable}

class AppStructure(pkgList : List[String]) extends Structure with Ensure{

  val allEntityClasses = mutable.Set[Class[_]]()
  for(pkg <- pkgList){
    val classUnderPackage = loadEntities(pkg)
    allEntityClasses ++= classUnderPackage
  }

  loadAppVersion(allEntityClasses)


  def loadAppVersion(clzs : Set[Class[_]]) {
    println(clzs.size)
    for (originalEntity <- clzs) {
      val entity = new JpaEntityVersion(originalEntity)

      this.entityVersions += (entity.name.get -> entity)
    }
  }



  def loadEntities(pkg : Any) : Set[Class[_]]  = {
    notNull(pkg, "File should not be null")

    val stringList = TypeCase[List[String]]

    pkg match {
      case pkgs : String => {
        if(StringUtils.contains(pkgs, ",")){
          val pkgList = StringUtils.split(pkgs, ",").toList
          loadEntities(pkgList)
        }else{
          val thePackage : Reflections = new Reflections(pkgs);
          thePackage.getTypesAnnotatedWith(classOf[javax.persistence.Entity]).asScala;
        }
      }

      case stringList(sl) => {
        val entities  = Set[Class[_]]()

        for(pkgStr <- sl){
          val pkgForPakcage = loadEntities(pkgStr)
          entities  ++: pkgForPakcage
        }

        entities
      }

      case _ =>{
        throw new RequestUnsupportedException("Unalbe to deal with the request: " + pkg)
      }
    }
  }

  def getId: String = {
    "appStructure"
  }
}
